package extendsexamp.User;

import java.io.*;

/**
 * @author Administrator
 * 操作实现类：实现接口（HashMap 来实现用户操作的3个功能）
 */
public class UserDaoIO implements UserDao {

    @Override
    public void register(User user) {
        /*传入的user对象写入文件*/
        BufferedWriter bw = null;
        try {
            //创建字符缓冲流对象
            bw = new BufferedWriter(new FileWriter("d:\\user.txt", true));
            //将user对象的各属性以"--"为分隔符作为一行文本写入文件
            bw.write(user.getId() + "--" + user.getAge() + "--"
                    + user.getPassword() + "--" + user.getAge());
            //加入行分隔符
            bw.newLine();
            //刷新
            bw.flush();
        } catch (IOException e) {
            System.out.println("出现异常：" + e.getMessage());
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean login(String name, String password) {
        /*1.读取文件中的每一行数据
             创建字符缓冲流对象
             循环操作：
             调用该对象的readline()方法读取一行数据
        * 2.将相关的数据跟传入的name和password比较
        *    若相同 返回true
        * 3.最后返回false*/
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("d:\\user.txt"));
            String line = null;
            while ((line = br.readLine()) != null) {
                //读取到得一行记录line:2--lishi--123--20
                //将line以“--”分割，得到String数组
                String[] data = line.split("--");
                //取出数组中的第二，三个元素与传入的name和password比较
                if (data[1].equals(name) && data[2].equals(password)) {
                    return true;
                }
            }
        } catch (Exception e) {
            System.out.println("出现异常：" + e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return false;
        }


    }

    @Override
    public void queryAll() {
        /* 读取文件中所有数据*/
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("d:\\user.txt"));
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println("出现异常：" + e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

